const express = require('express');
const router = express.Router();
const User = require('../model/index')
//注册
router.post('/sign', async (req, res, next) => {
    try {
        const { username, password } = req.body;
        if (!username || !password) {
            return res.status(400).send(JSON.stringify({
                code: 0,
                msg: "用户名和密码不能为空"
            }))
        }
        const name = await User.findOne({ username })
        if (name) {
            return res.status(200).send(JSON.stringify({
                code: 0,
                msg: "用户名不能重复"
            }))
        }
        const user = new User({
            username,
            password,
            create_time: Date.now()
        })
        const data = await user.save();
        res.status(200).send(JSON.stringify({
            code: 1,
            msg: 'success',
            data
        }))
    } catch (error) {
        res.status(500).send(next(error))
    }

})
//登录
router.post('/login', async (req, res, next) => {
    try {
        const { username, password } = req.body;
        if (!username || !password) {
            return res.status(400).send(JSON.stringify({
                code: 0,
                msg: "用户名和密码不能为空"
            }))
        }
        const user = await User.findOne({ username, password })
        if (user) {
            return res.status(200).send(JSON.stringify({
                code: 0,
                msg: "success",
                data: user
            }))
        } else {
            res.status(200).send(JSON.stringify({
                code: 0,
                msg: '用户和密码不匹配'
            }))
        }
    } catch (error) {
        res.status(500).send(next(error))
    }
})
//查询用户
router.get('/find/:username', async (req, res, next) => {
    try {
        const { username } = req.params;
        if (!username) {
            return res.status(400).send(JSON.stringify({
                code: 0,
                msg: "用户名不能为空"
            }))
        }
        const user = await User.find({ username})
        if (user) {
            return res.status(200).send(JSON.stringify({
                code: 1,
                msg: "success",
                data: user
            }))
        } else {
            res.status(200).send(JSON.stringify({
                code: 0,
                msg: '用户不存在'
            }))
        }
    } catch (error) {
        res.status(500).send(next(error))
    }
})

module.exports = router;
